/**
 * 用人部门
 * */
import React, { useState, useEffect } from 'react';
import { Form, Checkbox, Select, Input, Row, Radio, Button, Divider, message } from 'antd';
import { withRouter } from 'umi';
import { BottomAction } from '@/components';
import { PageContainer } from '@/molecules';
import { useRequest, defaultFormatResult } from '@/hooks';
import { history } from 'umi';
import { getEmployeeInfoList } from '@/services/components/userform';
import { size } from 'lodash';
import EmployeeCard from '@/pages/EntryManage/components/EmployeeCard';
import { replaceToWaitEntry } from '@/pages/EntryManage/utils';
import useCandidateProcess from '@/pages/EntryManage/hooks/useCandidateProcess';
import Card from '../../components/Card';
import styles from './index.less';
import { getEquipment, getSystem, getSoftSelected, postPrepareByDepartment } from '../services';
import { getSoft, getArrangedInfoByDepartment } from '../../services';
import Equipment from '../component/Equipment';
import SoftwarePreinstall from '../component/SoftwarePreinstall';

const { Option } = Select;
const { TextArea } = Input;
const formItemLayout = {
    labelCol: {
        span: 5
    },
    wrapperCol: {
        span: 18
    }
};

// 部门准备;
const PROCESS_STATUS = 2;
const EmployingDepartment = ({ form, location }) => {
    const { getFieldDecorator, validateFieldsAndScroll, setFieldsValue } = form;
    const [softTableData, setSoftTableData] = useState([]);
    const [softSelectData, setSoftSelectData] = useState([]);
    const [customSoftData, setCustomSoftData] = useState([]);
    const [loadingType, setLoadingType] = useState(0);

    const user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {};
    const { employeeCode } = user;

    const { entryPersonnelCode } = location.query;

    const handleCancel = () => {
        replaceToWaitEntry();
    };
    // 电脑配置
    const { loading: deviceDataLoading, data: deviceData, run: fetchEquipment } = useRequest(
        () => getEquipment({ entryPersonnelCode, choiceType: 0 }),
        {
            manual: true,
            ...defaultFormatResult
        }
    );
    // 获取虚拟资产
    const { data: systemList, run: fetchSystem, loading: systemListLoading } = useRequest(
        () => getSystem(entryPersonnelCode),
        {
            manual: true,
            ...defaultFormatResult
        }
    );
    // 获取通用软件
    const { loading: softListLoading, data: softList, run: fetchSoft } = useRequest(
        () => getSoft({ entryPersonnelCode }),
        {
            manual: true,
            ...defaultFormatResult
        }
    );
    // 获取已选择软件
    const { loading: softSelectedListLoading, data: softSelectedList, run: fetchSoftSelected } = useRequest(
        () => getSoftSelected({ entryPersonnelCode, choiceType: 0 }),
        {
            manual: true,
            ...defaultFormatResult
        }
    );
    // 获取带教人
    const { data: employeeList, loading: employeeLoading, run: fetchEmployeeInfoList } = useRequest(
        () => getEmployeeInfoList(),
        {
            manual: true,
            ...defaultFormatResult
        }
    );

    // 提交用人部门准备信息
    const { run: submitPrepareByDepartment, loading: submitLoading } = useRequest(
        value => postPrepareByDepartment(value),
        {
            manual: true,
            onSuccess: res => {
                if (res) {
                    const { code, msg } = res;

                    if (code === 10000) {
                        message.success(msg);
                        history.push({
                            pathname: '/office/personnelManagement/onboardAndLeave/entryManage/waitEntry'
                        });
                    } else {
                        message.error(msg);
                    }
                }
            }
        }
    );

    // 回退显示回填数据
    const { data: arrangedInfoByDepartmentData } = useRequest(() => getArrangedInfoByDepartment(entryPersonnelCode), {
        ...defaultFormatResult
    });
    // 校验是否当前是否可以提交
    const canAction = useCandidateProcess(entryPersonnelCode, PROCESS_STATUS, employeeCode);

    useEffect(() => {
        if (size(arrangedInfoByDepartmentData) > 0) {
            const {
                teacher,
                workArrangement,
                computerType,
                systemType,
                needDisplay,
                needMouse,
                softNameList,
                moreSoftwareList,
                systemList: systemListEcho,
                officeLocationCode,
                stationCode
            } = arrangedInfoByDepartmentData;
            setFieldsValue({
                teacher: teacher.length < 1 ? undefined : teacher,
                workArrangement,
                computerType,
                systemType,
                needDisplay,
                needMouse,
                softwareList: softNameList,
                moreSoftwareList,
                systemList: systemListEcho,
                officeLocationCode: officeLocationCode.length < 1 ? undefined : officeLocationCode,
                stationCode: stationCode.length < 1 ? undefined : stationCode
            });
            // 带教人值回填
            // setSelectEmployeeCode(teacher);
            // 获取办公工位
            // if (officeLocationCode) {
            //     fetchOfficeStation(officeLocationCode);
            // }
        }
    }, [arrangedInfoByDepartmentData, setFieldsValue]);

    const handleSubmit = type => {
        setLoadingType(type);
        // type === 0 为暂存 不做校验
        if (type === 1) {
            const {
                computerType,
                needDisplay,
                needMouse,
                systemType,
                moreSoftwareList,
                officeLocationCode,
                softwareList,
                stationCode,
                systemList: systemListData,
                workArrangement,
                teacher
            } = form.getFieldsValue();
            const param = {
                currentHandlerEmployeeCode: employeeCode,
                moreSoftwareList,
                officeLocationCode,
                softwareList,
                stationCode,
                systemList: systemListData,
                workArrangement,
                entryPersonnelCode,
                teacher,
                temporaryStorage: type, // type 是否暂存 0：否 1：是
                distributionDeviceVO: { computerType, needDisplay, needMouse, systemType }
            };
            submitPrepareByDepartment(param);
            return;
        }
        validateFieldsAndScroll({ scroll: { alignWithTop: true } }, (err, value) => {
            if (!err) {
                const {
                    computerType,
                    needDisplay,
                    needMouse,
                    systemType,
                    moreSoftwareList,
                    officeLocationCode,
                    softwareList,
                    stationCode,
                    systemList: systemListData,
                    workArrangement,
                    teacher
                } = value;
                const param = {
                    currentHandlerEmployeeCode: employeeCode,
                    moreSoftwareList,
                    officeLocationCode,
                    softwareList,
                    stationCode,
                    systemList: systemListData,
                    workArrangement,
                    entryPersonnelCode,
                    teacher,
                    temporaryStorage: type, // type 是否暂存 0：否 1：是
                    distributionDeviceVO: { computerType, needDisplay, needMouse, systemType }
                };
                submitPrepareByDepartment(param);
            }
        });
    };

    useEffect(() => {
        if (size(softList) > 0) {
            // 将数据源进行分类
            setSoftTableData(softList.filter(item => item.softClass === 0));
            setSoftSelectData(softList.filter(item => item.softClass === 1));
            setCustomSoftData(softList.filter(item => item.softClass === 2));
        }
    }, [softList]);
    useEffect(() => {
        fetchSystem();
        fetchEmployeeInfoList();
        fetchSoft();
        fetchEquipment();
        fetchSoftSelected();
    }, []);

    return (
        <PageContainer className={styles.employingDepartmentWrap}>
            <EmployeeCard employeeCode={entryPersonnelCode} isShowControls={false} />

            <Divider />
            <Card
                title="工作安排"
                headBorder
                bordered={false}
                extra={
                    canAction ? (
                        <BottomAction>
                            <span className={styles.autoNotice}>自行通知IT负责人</span>
                            <Button onClick={handleCancel}>取消</Button>
                            <Button
                                type="link"
                                style={{ border: '1px solid #FF9E00' }}
                                onClick={() => handleSubmit(1)}
                                loading={submitLoading && loadingType === 1}
                            >
                                保存
                            </Button>
                            <Button
                                type="primary"
                                onClick={() => handleSubmit(0)}
                                loading={submitLoading && loadingType === 0}
                            >
                                确定
                            </Button>
                        </BottomAction>
                    ) : null
                }
            >
                <Row>
                    <Form {...formItemLayout} className={styles.formBox}>
                        <Form.Item label="带教人">
                            {getFieldDecorator('teacher', {
                                rules: [{ required: true, message: '请输入' }]
                            })(
                                <Select
                                    loading={employeeLoading}
                                    showSearch
                                    // onSelect={onSelect}
                                    optionFilterProp="children"
                                    placeholder="请选择"
                                    getPopupContainer={triggerNode => triggerNode.parentElement}
                                    disabled={!canAction}
                                >
                                    {employeeList &&
                                        employeeList.map(item => (
                                            <Option
                                                value={item.employeeCode}
                                                key={item.employeeCode}
                                                code={item.employeeCode}
                                            >
                                                {item.employeeName}
                                            </Option>
                                        ))}
                                </Select>
                            )}
                        </Form.Item>
                        <Form.Item label="工作安排">
                            {getFieldDecorator('workArrangement', {
                                rules: [{ required: true, message: '请输入' }]
                            })(
                                <TextArea
                                    rows={4}
                                    placeholder="请输入入职初期的工作安排"
                                    maxLength={3000}
                                    disabled={!canAction}
                                />
                            )}
                        </Form.Item>
                        <Divider />
                        <Card
                            title="电脑配备"
                            headBorder
                            bordered={false}
                            className={styles.cardBox}
                            loading={deviceDataLoading}
                        >
                            <Equipment data={deviceData} />
                            <header>
                                <p>请为新员工选择合适的电脑配置：</p>
                            </header>
                            <Form.Item label="电脑类型">
                                {getFieldDecorator('computerType', {
                                    initialValue: 0,
                                    rules: [{ required: true, message: '请选择' }]
                                })(
                                    <Radio.Group disabled={!canAction}>
                                        <Radio value={0}>笔记本电脑</Radio>
                                        <Radio value={1}>台式整机</Radio>
                                    </Radio.Group>
                                )}
                            </Form.Item>
                            <Form.Item label="系统类型">
                                {getFieldDecorator('systemType', {
                                    initialValue: 0,
                                    rules: [{ required: true, message: '请选择' }]
                                })(
                                    <Radio.Group disabled={!canAction}>
                                        <Radio value={0}>windows</Radio>
                                        <Radio value={1}>Mac os</Radio>
                                        <Radio value={2}>Linux</Radio>
                                    </Radio.Group>
                                )}
                            </Form.Item>
                            <Form.Item label="需要显示器">
                                {getFieldDecorator('needDisplay', {
                                    initialValue: 1,
                                    rules: [{ required: true, message: '请选择' }]
                                })(
                                    <Radio.Group disabled={!canAction}>
                                        <Radio value={1}>是</Radio>
                                        <Radio value={0}>否</Radio>
                                    </Radio.Group>
                                )}
                            </Form.Item>
                            <Form.Item label="需要鼠标">
                                {getFieldDecorator('needMouse', {
                                    initialValue: 1,
                                    rules: [{ required: true, message: '请选择' }]
                                })(
                                    <Radio.Group disabled={!canAction}>
                                        <Radio value={1}>是</Radio>
                                        <Radio value={0}>否</Radio>
                                    </Radio.Group>
                                )}
                            </Form.Item>
                        </Card>
                        <Divider />
                        <Card
                            title="预装软件"
                            headBorder
                            bordered={false}
                            className={styles.cardBox}
                            loading={softSelectedListLoading || softListLoading}
                        >
                            <SoftwarePreinstall selected={softSelectedList} tableData={softTableData} />
                            <header>
                                <p>请为新员工选择合适的软件：</p>
                            </header>
                            <Form.Item label="专业软件">
                                {getFieldDecorator('softwareList')(
                                    <Select
                                        mode="tags"
                                        placeholder="请选择"
                                        getPopupContainer={triggerNode => triggerNode.parentElement}
                                        disabled={!canAction}
                                    >
                                        {softSelectData &&
                                            softSelectData.map(item => (
                                                <Option value={item.softName} key={item.softCode}>
                                                    {item.softName}
                                                </Option>
                                            ))}
                                    </Select>
                                )}
                            </Form.Item>
                            <Form.Item label="更多软件">
                                {getFieldDecorator('moreSoftwareList')(
                                    <Select mode="tags">
                                        {customSoftData &&
                                            customSoftData.map(item => (
                                                <Option value={item.softName} key={item.softCode}>
                                                    {item.softName}
                                                </Option>
                                            ))}
                                    </Select>
                                )}
                            </Form.Item>
                        </Card>

                        <Divider />
                        <Card title="虚拟资产" headBorder bordered={false} loading={systemListLoading}>
                            <Form.Item
                                label="使用系统"
                                help="请选择新员工需要使用的系统，将由IT人员为其开通相关系统的账号"
                            >
                                {getFieldDecorator('systemList', {
                                    rules: [{ required: true, message: '请输入xxxx' }]
                                })(
                                    <Checkbox.Group disabled={!canAction}>
                                        {systemList &&
                                            systemList.map(item => (
                                                <Checkbox
                                                    value={item.assetCode}
                                                    key={item.assetCode}
                                                    checked={item.mandatory === 1}
                                                    disabled={item.mandatory === 1}
                                                >
                                                    {item.assetName}
                                                </Checkbox>
                                            ))}
                                    </Checkbox.Group>
                                )}
                            </Form.Item>
                        </Card>
                    </Form>
                </Row>
            </Card>
        </PageContainer>
    );
};
export default withRouter(Form.create()(EmployingDepartment));
